<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Db;
use think\Model;
class Outsourcing extends Model
{

    // 表名
    protected $name = 'kuyou_outsourcing';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->page($page,$limit)->order(['id'=>'DESC'])->field('id,purchase_code,customers_id,production_code,plan_code,purchase_time,work_time,finish_time,workshop_id,number,all_money,free_money,examine_id,examine_time,preparation_id,examine_id,operation_id,status,examine_status')->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order(['id'=>'DESC'])->field('id,purchase_code,customers_id,production_code,plan_code,purchase_time,work_time,finish_time,workshop_id,number,all_money,free_money,examine_id,examine_time,preparation_id,examine_id,operation_id,status,examine_status')->select())->toArray();
        }
        $adminList = (new Commons())->adminList();
        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['customers_id'] = Db::name('kuyou_customers')->where(['id'=>$list_v['customers_id']])->value('customer_name');
            $production_id = Db::name('kuyou_plan')->where(['purchase_code'=>$list_v['plan_code']])->value('id');
            $goods_list = Db::name('kuyou_plan_info')->where(['plan_id'=>$production_id])->field('goods_name,number')->select();
            $str = '';
            foreach ($goods_list as $goods_list_k=>$goods_list_v){
                $str .= $goods_list_v['goods_name'].'*'.$goods_list_v['number'].' ';
            }
            $list[$list_k]['goods_info'] = $str;

            $list[$list_k]['purchase_time'] = date('Y-m-d',$list_v['purchase_time']);
            if(!empty($list_v['examine_time']) && $list_v['examine_status']==1){
                $list[$list_k]['examine_time'] = date('Y-m-d',$list_v['examine_time']);
            }else{
                $list[$list_k]['examine_time'] = '';
            }
            $list[$list_k]['examine_name'] = isset($adminList[$list_v['examine_id']])?$adminList[$list_v['examine_id']]:'';
            $list[$list_k]['preparation_name'] = isset($adminList[$list_v['preparation_id']])?$adminList[$list_v['preparation_id']]:'';
            $list[$list_k]['operation_name'] = isset($adminList[$list_v['operation_id']])?$adminList[$list_v['operation_id']]:'';
            $list[$list_k]['work_time'] = date('Y-m-d H:i:s',$list_v['work_time']);
            $list[$list_k]['finish_time'] = date('Y-m-d H:i:s',$list_v['finish_time']);
        }

        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param int $id
     * @return array
     */
    public static function getDetail($id){
        $detail = self::where(function ($query) use ($id) {
            $query->where('id', '=', $id);
        })->field('id,purchase_code,production_code,customers_id,plan_code,purchase_time,work_id,work_time,finish_time,workshop_id,number,all_money,free_money,examine_id,examine_time,preparation_id,examine_id,operation_id,status,examine_status,remark')->find();
        if($detail){
            $adminList = (new Commons())->adminList();
            $detail['purchase_time'] = date('Y-m-d',$detail['purchase_time']);
            if(!empty($detail['examine_time']) && $detail['examine_status']==1){
                $detail['examine_time'] = date('Y-m-d',$detail['examine_time']);
            }else{
                $detail['examine_time'] = '';
            }
            $detail['examine_name'] = isset($adminList[$detail['examine_id']])?$adminList[$detail['examine_id']]:'';
            $detail['preparation_name'] = isset($adminList[$detail['preparation_id']])?$adminList[$detail['preparation_id']]:'';
            $detail['operation_name'] = isset($adminList[$detail['operation_id']])?$adminList[$detail['operation_id']]:'';
            $detail['work_name'] = Db::name('kuyou_staff_member')->where(['id'=>$detail['work_id']])->value('name');
            $detail['work_time'] = date('Y-m-d H:i:s',$detail['work_time']);
            $detail['finish_time'] = date('Y-m-d H:i:s',$detail['finish_time']);

            $detail['customers_name'] = Db::name('kuyou_factory')->where(['id'=>$detail['customers_id']])->value('customer_name');
            $production_id = Db::name('kuyou_plan')->where(['purchase_code'=>$detail['plan_code']])->value('id');
            $goods_list = Db::name('kuyou_plan_info')->where(['plan_id'=>$production_id])->field('goods_name,number')->select();
            $str = '';
            foreach ($goods_list as $goods_list_k=>$goods_list_v){
                $str .= $goods_list_v['goods_name'].'*'.$goods_list_v['number'].' ';
            }
            $detail['goods_info'] = $str;

            $purchase_info = Db::name('kuyou_outsourcing_info')->where(['production_id'=>$detail['id']])->select();
            $unit = Db::name('kuyou_unit')->column('name','id');
            foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                $goods_info = (new Goods())->where(['goods_code'=>$purchase_info_v['goods_code']])->find();
                $purchase_info[$purchase_info_k]['goods_info'] = $goods_info;
                $purchase_info[$purchase_info_k]['goods_image'] = $goods_info['goods_image'];
                $purchase_info[$purchase_info_k]['unit'] = (new Goods())->getGoodsUnit($purchase_info_v['goods_id']);
                $purchase_info[$purchase_info_k]['unit_name'] = isset($unit[$purchase_info_v['unit_id']])?$unit[$purchase_info_v['unit_id']]:'';
                $purchase_info[$purchase_info_k]['default_unit_name'] = isset($unit[$purchase_info_v['default_unit']])?$unit[$purchase_info_v['default_unit']]:'';
                if(!empty($purchase_info_v['period'])){
                    $purchase_info[$purchase_info_k]['period'] = unserialize($purchase_info_v['period']);
                }
            }
            $detail['info_list'] = $purchase_info;
            return ['status'=>200,'msg'=>$detail];
        }else{
            return ['status'=>500,'msg'=>'未查询到相关信息'];
        }
    }

    /**
     * 获取详情
     * @param int $id
     * @return array
     */
    public static function planinfo($purchase_code){
        $plan = Db::name('kuyou_plan')->where(['purchase_code'=>$purchase_code])->find();
        if($plan){
            $info = Db::name('kuyou_plan_info')->where(['plan_id'=>$plan['id']])->select();
            $unit = Db::name('kuyou_unit')->column('name','id');
            $data = [];
            foreach ($info as $info_k=>$info_v){
                $bom = Db::name('kuyou_bom')->where(['goods_code'=>$info_v['goods_code']])->column('id');
                $info_id = Db::name('kuyou_bom_info')->where(['bom_id'=>['in',$bom]])->select();
                foreach ($info_id as $info_id_k=>$info_id_v){
                    $info_id_v['number'] = $info_id_v['number']*$info_v['number'];
                    $info_id_v['basic_nmber'] = $info_id_v['basic_nmber']*$info_v['number'];
                    $info_id_v['money'] = $info_id_v['money']*$info_v['number'];

                    $goods_info = (new Goods())->where(['id'=>$info_id_v['goods_id']])->find();
                    $info_id_v['goods_info'] = $goods_info;
                    $info_id_v['goods_image'] = $goods_info['goods_image'];

                    $info_id_v['unit'] = (new Goods())->getGoodsUnit($info_id_v['goods_id']);
                    $info_id_v['unit_name'] = isset($unit[$info_id_v['unit_id']])?$unit[$info_id_v['unit_id']]:'';
                    $info_id_v['default_unit_name'] = isset($unit[$info_id_v['default_unit']])?$unit[$info_id_v['default_unit']]:'';

                    $data[] = $info_id_v;
                }
            }
            return ['status'=>200,'msg'=>$data];
        }else{
            return ['status'=>500,'msg'=>'查询失败'];
        }
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'plan_code|生产计划编号' =>'require',
                'purchase_code|单据编号' =>'require',
                'purchase_time|单据时间'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $status = (new Commons())->checkCode($detail['purchase_code'],35);//验证编号是否合法
                if(!$status){
                    return ['status'=>500,'msg'=>'单据编号格式错误'];
                }
                $row = (new Outsourcing())->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                if($row){
                    return ['status'=>500,'msg'=>'编号已存在'];
                }
                $examine= (new Commons())->getSet('examine','is_checked');
                $set= (new Commons())->getSet('serial','is_checked');
                $batch= (new Commons())->getSet('batch','is_checked');
                $detail['info_list'] = (array)json_decode($detail['info_list'], true);

                $data = [];
                $number = 0;$all_money = 0;
                foreach ($detail['info_list'] as $k=>$v){
                    if(!empty($v['goods_code'])){//有产品编号
                        $number += (float)$v['number'];
                        $all_money += (float)$v['all_money'];
                        $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->field('id,goods_name,serial,batch,auxiliary')->find();
                        if(!isset($v['stores_id']) || empty($v['stores_id'])){
                            return ['status'=>500,'msg'=>'请选择'.$goods['goods_name'].'仓库'];
                        }
                        $batch_data = Db::name('kuyou_goods_batch')->where(['id'=>$v['batch_id']])->find();

                        if($goods['auxiliary']==1 && empty($v['goods_attr'])){
                            return ['status'=>500,'msg'=>'请选择'.$goods['goods_name'].'属性'];
                        }

                        if($goods['batch']==1 && $batch==1){
                            if(empty($v['batch_id'])){
                                return ['status'=>500,'msg'=>'请选择'.$goods['goods_name'].'生产批次'];
                            }
                            if(empty($batch_data)){
                                return ['status'=>500,'msg'=>$goods['goods_name'].'生产批次不存在'];
                            }
                        }

                        $serial_code = [];
                        if(isset($v['period_period']) && $goods['serial']==1 && $set==1){
                            if(empty($v['period_period'])){
                                return ['status'=>500,'msg'=>'请输入'.$goods['goods_name'].'商品序列号'];
                            }

                            $period_period = $v['period_period'];
                            try{
                                $period_period = unserialize($v['period_period']);
                            }catch (\Exception $e){
                            }
                            if(!is_array($period_period)){
                                $period_period = (array)json_decode($v['period_period'], true);
                            }
                            $v['period_period'] = serialize($period_period);

                            foreach ($period_period as $period_period_k=>$period_period_v){
                                $serial_code[] = $period_period_v['serial'];
                            }
                            $where = [];
                            $where['serial'] = ['in',$serial_code];
                            $goods_serial = Db::name('kuyou_goods_serial')->where($where)->column('serial');
                            if(empty($goods_serial)){
                                return ['status'=>500,'msg'=>$goods['goods_name'].'商品序列号不存在'];
                            }
                            foreach ($serial_code as $serial_code_k=>$serial_code_v){
                                if(!in_array($serial_code_v,$goods_serial)){
                                    return ['status'=>500,'msg'=>$serial_code_v.'商品序列号不存在'];
                                }
                            }
                            $goods_serials = Db::name('kuyou_goods_serial')->where(['store_status'=>['in',[0,2]],'serial'=>['in',$serial_code]])->column('serial');
                            if(!empty($goods_serials)){
                                $goods_serials = implode(',',$goods_serials);
                                return ['status'=>500,'msg'=>'商品序列号'.$goods_serials.'已经待出库，不可重复出库'];
                            }
                        }

                        $data[] = [
                            'type'          =>  2,
                            'goods_id'      =>  $goods['id'],
                            'goods_code'    =>  $v['goods_code'],
                            'goods_name'    =>  $goods['goods_name'],
                            'goods_note'    =>  $v['goods_note'],
                            'unit_id'       =>  (float)$v['goods_unit'],
                            'default_unit'  =>  (float)$v['default_unit'],
                            'purchase'      =>  (float)$v['unit_price'],
                            'number'        =>  (float)$v['number'],
                            'basic_nmber'   =>  (float)$v['basic_nmber'],
                            'money'         =>  (float)$v['all_money'],
                            'stores_id'     =>  (float)$v['stores_id'],
                            'allow_stock'   =>  (float)$v['allow_stock'],
                            'stock_number'  =>  0,
                            'need_number'   =>  (float)$v['all_money'],
                            'goods_attr'    =>  (float)$v['goods_attr'],
                            'remark'        =>  $v['remark'],
                            'batch_id'      => isset($batch_data['id'])?$batch_data['id']:null,
                            'batch_name'    => isset($batch_data['batch_name'])?$batch_data['batch_name']:null,
                            'manufacture'   => !empty($v['manufacture'])?strtotime($v['manufacture']):null,
                            'guarantee'     => !empty($v['guarantee'])?$v['guarantee']:null,
                            'validity'      => !empty(strtotime($v['validity']))?strtotime($v['validity']):null,
                            'period'        =>  $v['period_period']===''?null:$v['period_period'],
                            'createtime'    => time(),
                            'updatetime'    => time(),
                        ];
                    }
                }

                $plan = Db::name('kuyou_plan')->where(['purchase_code'=>$detail['plan_code']])->find();
                if(empty($plan)){
                    return ['status'=>500,'msg'=>'生产计划查询失败'];
                }
                if(empty($data)){
                    return ['status'=>500,'msg'=>'请填写详情数据'];
                }else{
                    $admin = (new Commons())->getAdminId();
                    if(isset($plan['id'])){
                        unset($plan['id']);
                    }
                    $row = $plan;
                    $row['plan_code'] = $detail['plan_code'];
                    $row['purchase_code'] = $detail['purchase_code'];
                    $row['purchase_time'] = strtotime($detail['purchase_time']);
                    $row['work_time'] = strtotime($detail['work_time']);
                    $row['finish_time'] = strtotime($detail['finish_time']);
                    $row['remark'] = $detail['remark'];
                    $row['work_id'] = $detail['work_id'];
                    $row['number'] = $number;
                    $row['all_money'] = $all_money;
                    $row['free_money'] = (float)$detail['free_money'];
                    $row['customers_id'] = (float)$detail['customers_id'];
                    $row['examine_status'] = '0';
                    $row['createtime'] = time();
                    $row['updatetime'] = time();
                    $row['preparation_id'] = $admin;
                    $row['operation_id'] = $admin;
                }

                $res = false;
                Db::startTrans();
                try {
                    $res = (new Outsourcing())->insertGetId($row);
                    foreach ($data as $data_k=>$data_v){
                        $data[$data_k]['production_id'] = $res;
                    }
                    Db::name('kuyou_outsourcing_info')->insertAll($data);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $res = false;$msg = $e->getMessage();
                }
                if($res){
                    if($examine!=1){
                        try {
                            $exa = self::examine($res);
                        } catch (\Exception $e) {
                        }
                        if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                            try {
                                self::delDetail($res);
                            } catch (\Exception $e) {
                            }
                            return ['status'=>500,'msg'=>$exa['msg']];
                        }
                    }
                    return ['status'=>200,'msg'=>$res];
                }else{
                    return ['status'=>500,'msg'=>(isset($msg)?$msg:'添加失败')];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'id|ID'=>'require|number',
                'plan_code|生产计划编号' =>'require',
                'purchase_code|单据编号' =>'require',
                'purchase_time|单据时间'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $status = (new Commons())->checkCode($detail['purchase_code'],35);//验证编号是否合法
                if(!$status){
                    return ['status'=>500,'msg'=>'单据编号格式错误'];
                }
                $row = (new Outsourcing())->where(['purchase_code'=>$detail['purchase_code'],'id'=>['<>',$detail['id']]])->value('id');
                if($row){
                    return ['status'=>500,'msg'=>'编号已存在'];
                }
                $examine= (new Commons())->getSet('examine','is_checked');
                $set= (new Commons())->getSet('serial','is_checked');
                $batch= (new Commons())->getSet('batch','is_checked');
                $id = $detail['id'];unset($detail['id']);

                $model = new Outsourcing();
                $row = $model->where(['id'=>$id])->find();
                if(empty($row)){
                    return ['status'=>500,'msg'=>'修改的单据不存在'];
                }
                if($examine==1 && $row['examine_status']==1){
                    return ['status'=>500,'msg'=>'不可修改已审核的单据'];
                }
                $detail['info_list'] = (array)json_decode($detail['info_list'], true);

                $data = [];
                $number = 0;$all_money = 0;
                foreach ($detail['info_list'] as $k=>$v){
                    if(!empty($v['goods_code'])){//有产品编号
                        $number += (float)$v['number'];
                        $all_money += (float)$v['all_money'];
                        $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->field('id,goods_name,serial,batch,auxiliary')->find();
                        if(!isset($v['stores_id']) || empty($v['stores_id'])){
                            return ['status'=>500,'msg'=>'请选择'.$goods['goods_name'].'仓库'];
                        }
                        if($goods['auxiliary']==1 && empty($v['goods_attr'])){
                            return ['status'=>500,'msg'=>'请选择'.$goods['goods_name'].'属性'];
                        }
                        $batch_data = Db::name('kuyou_goods_batch')->where(['id'=>$v['batch_id']])->find();
                        if($goods['batch']==1 && $batch==1){
                            if(empty($v['batch_id'])){
                                return ['status'=>500,'msg'=>'请选择'.$goods['goods_name'].'生产批次'];
                            }
                            if(empty($batch_data)){
                                return ['status'=>500,'msg'=>$goods['goods_name'].'生产批次不存在'];
                            }
                        }

                        $serial_code = [];
                        if(isset($v['period_period']) && $goods['serial']==1 && $set==1){
                            if(empty($v['period_period'])){
                                return ['status'=>500,'msg'=>'请输入'.$goods['goods_name'].'商品序列号'];
                            }

                            $period_period = $v['period_period'];
                            try{
                                $period_period = unserialize($v['period_period']);
                            }catch (\Exception $e){
                            }
                            if(!is_array($period_period)){
                                $period_period = (array)json_decode($v['period_period'], true);
                            }
                            $v['period_period'] = serialize($period_period);

                            foreach ($period_period as $period_period_k=>$period_period_v){
                                $serial_code[] = $period_period_v['serial'];
                            }
                            $where = [];
                            $where['serial'] = ['in',$serial_code];
                            $goods_serial = Db::name('kuyou_goods_serial')->where($where)->column('serial');
                            if(empty($goods_serial)){
                                return ['status'=>500,'msg'=>$goods['goods_name'].'商品序列号不存在'];
                            }
                            foreach ($serial_code as $serial_code_k=>$serial_code_v){
                                if(!in_array($serial_code_v,$goods_serial)){
                                    return ['status'=>500,'msg'=>$serial_code_v.'商品序列号不存在'];
                                }
                            }
                            $goods_serials = Db::name('kuyou_goods_serial')->where(['store_status'=>['in',[0,2]],'serial'=>['in',$serial_code]])->column('serial');
                            if(!empty($goods_serials)){
                                $goods_serials = implode(',',$goods_serials);
                                return ['status'=>500,'msg'=>'商品序列号'.$goods_serials.'已经待出库，不可重复出库'];
                            }
                        }

                        $data[] = [
                            'type'          =>  2,
                            'goods_id'      =>  $goods['id'],
                            'goods_code'    =>  $v['goods_code'],
                            'goods_name'    =>  $goods['goods_name'],
                            'goods_note'    =>  $v['goods_note'],
                            'unit_id'       =>  (float)$v['goods_unit'],
                            'default_unit'  =>  (float)$v['default_unit'],
                            'purchase'      =>  (float)$v['unit_price'],
                            'number'        =>  (float)$v['number'],
                            'basic_nmber'   =>  (float)$v['basic_nmber'],
                            'money'         =>  (float)$v['all_money'],
                            'stores_id'     =>  (float)$v['stores_id'],
                            'allow_stock'   =>  (float)$v['allow_stock'],
                            'stock_number'  =>  0,
                            'need_number'   =>  (float)$v['all_money'],
                            'goods_attr'    =>  (float)$v['goods_attr'],
                            'remark'        =>  $v['remark'],
                            'batch_id'      => isset($batch_data['id'])?$batch_data['id']:null,
                            'batch_name'    => isset($batch_data['batch_name'])?$batch_data['batch_name']:null,
                            'manufacture'   => !empty($v['manufacture'])?strtotime($v['manufacture']):null,
                            'guarantee'     => !empty($v['guarantee'])?$v['guarantee']:null,
                            'validity'      => !empty(strtotime($v['validity']))?strtotime($v['validity']):null,
                            'period'        =>  $v['period_period']===''?null:$v['period_period'],
                            'createtime'    => time(),
                            'updatetime'    => time(),
                        ];
                    }
                }

                $plan = Db::name('kuyou_plan')->where(['purchase_code'=>$detail['plan_code']])->find();
                if(empty($plan)){
                    return ['status'=>500,'msg'=>'生产计划查询失败'];
                }
                if(empty($data)){
                    return ['status'=>500,'msg'=>'请填写详情数据'];
                }else{
                    $admin = (new Commons())->getAdminId();
                    if(isset($plan['id'])){
                        unset($plan['id']);
                    }
                    $rowdata = $plan;
                    $rowdata['plan_code'] = $detail['plan_code'];
                    $rowdata['purchase_code'] = $detail['purchase_code'];
                    $rowdata['purchase_time'] = strtotime($detail['purchase_time']);
                    $rowdata['work_time'] = strtotime($detail['work_time']);
                    $rowdata['finish_time'] = strtotime($detail['finish_time']);
                    $rowdata['remark'] = $detail['remark'];
                    $rowdata['work_id'] = $detail['work_id'];
                    $rowdata['free_money'] = (float)$detail['free_money'];
                    $rowdata['customers_id'] = (float)$detail['customers_id'];
                    $rowdata['number'] = $number;
                    $rowdata['examine_status'] = '0';
                    $rowdata['all_money'] = $all_money;
                    $rowdata['updatetime'] = time();
                    $rowdata['preparation_id'] = $admin;
                    $rowdata['operation_id'] = $admin;
                }

                $res = false;
                Db::startTrans();
                try {
                    //关闭审核功能需先反审核一次已审核数据
                    $exa['status']=1;
                    if($examine!=1 && $row['examine_status']==1){
                        $exa = self::examinef($id);
                    }
                    if(isset($exa['status']) && $exa['status']==1){
                        if(!empty($rowdata)){
                            $res = $model->where(['id'=>$id])->update($rowdata);
                        }

                        foreach ($data as $data_k=>$data_v){
                            $data[$data_k]['production_id'] = $id;
                        }
                        Db::name('kuyou_outsourcing_info')->where(['production_id'=>$id])->delete();
                        Db::name('kuyou_outsourcing_info')->insertAll($data);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $res = false;$msg = $e->getMessage();
                }

                if($res){
                    if($examine!=1){
                        try {
                            $exa = self::examine($id);
                        } catch (\Exception $e) {
                        }
                        if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                            return ['status'=>500,'msg'=>$exa['msg']];
                        }
                    }
                    return ['status'=>200,'msg'=>'更新成功'];
                }else{
                    return ['status'=>500,'msg'=>(isset($msg)?$msg:'更新失败')];
                }
            }
        }
    }

    /**
     * 删除
     * @param int $id
     * @return array
     */
    public static function delDetail($id){
        if(empty($id)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $list = (new Outsourcing())->where(['id'=>['in',$id]])->select();
            $examine= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
            foreach ($list as $k=>$row){
                if($row['examine_status']==1 && $examine==1){
                    return ['status'=>500,'msg'=>'不能删除已审核的数据'];
                }
            }


            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $exa['status']=1;
                    if($v['examine_status']==1 && $examine==1){
                        exception('不能删除已审核的数据');
                    }elseif ($v['examine_status']==1 && $examine!=1){
                        try {
                            $exa = self::examine($v['id']);
                        } catch (\Exception $e) {
                        }
                    }
                    if(isset($exa['status']) && $exa['status']==1){
                        $count += $v->delete();
                        Db::name('kuyou_outsourcing_info')->where(['production_id'=>$v['id']])->delete();
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $count = 0;
            }

            if($count){
                return ['status'=>200,'msg'=>$count];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }

    /**
     * 审核
     * @param array $purchase_code
     * @return array
     */
    public static function examine($ids = null){
        if(empty($ids)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        $model = new Outsourcing();
        $list = $model->where(['id'=>['in',$ids],'examine_status'=>'0'])->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要审核的数据'];
        }

        $production_id = $model->where(['id'=>['in',$ids],'examine_status'=>'0'])->column('id');


        $purchase_info_id = Db::name('kuyou_outsourcing_info')->where(['production_id'=>['in',$production_id]])->column('id');
        $info_list = Db::name('kuyou_outsourcing_info')->where(['production_id'=>['in',$production_id]])->select();

        $editstock = [];
        $goods_stock = [];
        $purchase_info = [];
        $goods_stock_log = [];//收发详情
        $serial_log = [];//序列号跟踪
        $serial_data = [];
        foreach ($info_list as $list_k=>$list_v){
            $picking = Db::name('kuyou_outsourcing')->where(['id'=>$list_v['production_id']])->find();
            if(!empty($list_v['period'])){
                $goods_serial = unserialize($list_v['period']);
                foreach ($goods_serial as $goods_serial_k=>$goods_serial_v){
                    $this_serial = Db::name('kuyou_goods_serial')->where(['serial'=>$goods_serial_v['serial']])->find();
                    if(empty($this_serial)){
                        return ['status'=>500,'msg'=>'序列号'.$goods_serial_v['serial'].'不存在'];
                    }
                    $serial_data[] = [
                        'id'=>$this_serial['id'],
                        'sale_id' => $picking['id'],
                        'sale_code' => $picking['purchase_code'],
                        'status' => '3',
                        'store_status' => '2',
                        'old_status' => $this_serial['status'],
                        'old_store' => $this_serial['store_status'],
                    ];
                    $serial_log[] = [
                        'goods_id'=>$list_v['goods_id'],
                        'stores_id'=>$list_v['stores_id'],
                        'attribute_id'=>$list_v['goods_attr'],
                        'serial'=>$goods_serial_v['serial'],
                        'business_type'=>'15',
                        'store_status'=>'2',
                        'remarks' => $list_v['remark'],
                        'purchase_id'=>$list_v['id'],
                        'customer_id'=>null,
                        'purchase_code'=>$picking['purchase_code'],
                        'purchase_time' => $picking['purchase_time'],
                        'createtime'  => time(),
                        'updatetime'  => time(),
                    ];
                }
            }

            $info_list[$list_k]['sales_order_id']    = $list_v['id'];
            $info_list[$list_k]['createtime']        = time();
            $info_list[$list_k]['updatetime']        = time();
            $stock_number = $list_v['basic_nmber'];
            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$list_v['goods_code']])->field('id,attribute_id,inventory,unit_id,goods_name')->find();
            $status = false;
            foreach ($goods_stock as $goods_stock_k=>$goods_stock_v){
                if($goods_stock_v['id']==$goods['id']){
                    $goods_stock[$goods_stock_k]['inventory'] = $goods_stock_v['inventory']-$stock_number;
                    $status = true;
                }
            }
            if(!$status){
                $goods_stock[] = [
                    'id'=>$goods['id'],
                    'inventory'=>$goods['inventory']-$stock_number,
                ];
            }
            //商品库存
            $where = [];
            $where['goods_code'] = $list_v['goods_code'];
            $where['stores_id'] = $list_v['stores_id'];
            if($list_v['goods_attr']>0){
                $goods_attr = $list_v['goods_attr'];
                if($goods_attr>0){
                    $where['attribute_id'] = $goods_attr;
                }
            }

            //获取成本单价
            $balance_cost=0;$balance_unit=0;
            $goodsInfo = json_decode((new Commons())->getUnit($list_v['goods_code'],$list_v['stores_id'],$list_v['goods_attr']),true);
            $unitData = isset($goodsInfo['unit'])?$goodsInfo['unit']:[];
            if(empty($unitData)){
                return ['status'=>500,'msg'=>'商品信息获取错误'];
            }else{
                foreach ($unitData as $unitData_k=>$unitData_v){
                    if($unitData_v['id']==$goods['unit_id']){
                        $balance_unit = $unitData_v['purchase'];
                    }
                }
            }
            //获取成本单价结束

            $stock = Db::name('kuyou_goods_stock')->where($where)->field('stock,id')->find();
            if($stock){
                $status = false;
                foreach ($editstock as $editstock_k=>$editstock_v){
                    if($editstock_v['id']==$stock['id']){
                        $editstock[$editstock_k]['stock'] -= $stock_number;
                        $status = true;
                        $balance_cost   = (round($balance_unit*$stock_number,4));
                    }
                }
                if(!$status){
                    $editstock[] = [
                        'id'=>$stock['id'],
                        'stock'=>(round($stock['stock']-$stock_number,4))
                    ];
                    $balance_cost   = (round($balance_unit*$stock_number,4));
                }
            }else{
                $store = Db::name('kuyou_stores')->where(['id'=>$list_v['stores_id']])->value('name');
                return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].$store.'库存不足'];
            }
            $purchase_info[] = $list_v['id'];

            //收发详情
            if($goods){
                $goods_stock_log[] = [
                    'purchase_code' => $picking['purchase_code'],
                    'purchase_id'   => $list_v['id'],
                    'purchase_time' => $picking['purchase_time'],
                    'business_type' => '16',
                    'customer_id'   => null,
                    'goods_id'      => $goods['id'],
                    'goods_code'    => $list_v['goods_code'],
                    'attribute_id'  => (float)$list_v['goods_attr'],
                    'goods_unit'    => (float)$list_v['unit_id'],
                    'stores_id'     => (float)$list_v['stores_id'],
                    'remark'        => $list_v['remark'],
                    'out_number'    => (float)$list_v['number'],
                    'out_basics'    => (float)$list_v['basic_nmber'],
                    'out_unit'      => $balance_unit,
                    'out_cost'      => $balance_cost,
                    'createtime'    => time(),
                    'updatetime'    => time(),
                ];
            }
            //收发详情结束
        }
        foreach ($editstock as $editstock_k=>$editstock_v){
            if($editstock_v['stock']<0){
                $store = Db::name('kuyou_stores')->where(['id'=>$list_v['stores_id']])->value('name');
                return ['status'=>500,'msg'=>$goods['goods_name'].$store.'库存不足,操作失败'];
            }
        }

        //批次库存数据
        //获取设置
        $set= \think\Db::name('kuyou_sets')->field('type,name,value,is_checked,set')->select();
        $setList = [];
        foreach ($set as $set_k=>$set_v){
            if(!empty($set_v['set'])){
                $set_v['set'] = unserialize($set_v['set']);
            }
            $setList[$set_v['name']] = $set_v;
        }
        //数量价格格式化
        $number_decimal = $setList['number_decimal']['value'];
        $goods_serial = Db::name('kuyou_outsourcing_info')->where(['id'=>['in',$purchase_info_id]])->select();

        $goods_batch_add = [];$goods_batch_edit = [];$goods_batch_log = [];$goods_batch_info=[];
        foreach ($goods_serial as $k=>$v){
            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->field('id,goods_name,attribute_id,inventory,unit_id,batch')->find();
            if($goods['batch']==1){
                //先通过单位计算需修改多单位商品的库存数量
                if($goods['unit_id']==$v['unit_id']){
                    $stock_number = $v['number'];
                }else{
                    $unit_conversion = Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$v['goods_unit']])->value('advance_rate');
                    if(empty($unit_conversion)){
                        return ['status'=>500,'msg'=>'商品单位信息查询失败'];
                    }else{
                        $stock_number = round(($v['number']*$unit_conversion),$number_decimal);
                    }
                }

                $where = [];
                $where['goods_id'] = $goods['id'];
                if($v['goods_attr']){
                    $where['attribute_id'] = $v['goods_attr'];
                }
                $where['stores_id'] = $v['stores_id'];
                $where['batch_id'] = $v['batch_id'];
                $goods_batch_stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                if(empty($goods_batch_stock)){
                    $status = false;
                    foreach ($goods_batch_add as $goods_batch_add_k=>$goods_batch_add_v){
                        if($goods_batch_add_v['batch_id']==$v['batch_id'] && $goods_batch_add_v['goods_id']==$v['goods_id'] && $goods_batch_add_v['attribute_id']==$v['attribute_id'] && $goods_batch_add_v['stores_id']==$v['stores_id']){
                            $goods_batch_add[$goods_batch_add_k]['stock'] -= $stock_number;
                            $status = true;
                        }
                    }
                    if(!$status){
                        $goods_batch_add[] = [
                            'batch_id' => $v['batch_id'],
                            'goods_id' => $goods['id'],
                            'goods_code' => $v['goods_code'],
                            'attribute_id' => $v['goods_attr'],
                            'stores_id' => $v['stores_id'],
                            'stock' => $stock_number,
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                    }
                }else{
                    if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                        $goods_batch_edit[$goods_batch_stock['id']] -= $stock_number;
                    }else{
                        $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']-$stock_number;
                    }
                }
                foreach ($goods_batch_edit as $k2=>$v2){
                    if($v2<0){
                        return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'库存不足'];
                    }
                }

                //商品批次跟踪
                $goods_batch_log[] = [
                    'goods_id'      => $goods['id'],
                    'goods_unit'    => $v['unit_id'],
                    'stores_id'     => $v['stores_id'],
                    'batch_id'      => (float)$v['batch_id'],
                    'number'        => (float)$v['number'],
                    'purchase_code' => $picking['purchase_code'],
                    'purchase_time' => $picking['purchase_time'],
                    'business_type' => '15',
                    'remarks'       => $v['remark'],
                    'order_id'      => $v['id'],
                    'unit_price'    => $v['purchase'],
                    'all_money'     => $v['money'],
                    'createtime'    => time(),
                    'updatetime'    => time(),
                ];

                $batch_data = Db::name('kuyou_goods_batch')->where(['id'=>$v['batch_id']])->find();
                if(empty($batch_data)){
                    return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'批次查询失败'];
                }
                $goods_batch_info[] = [
                    'batch_id'    => isset($batch_data['id'])?$batch_data['id']:'',
                    'goods_id'    => $goods['id'],
                    'goods_code'  => $v['goods_code'],
                    'attribute_id'=> $v['goods_attr'],
                    'goods_unit'  => $v['unit_id'],
                    'stores_id'   => $v['stores_id'],
                    'stock'       => (float)$v['number'],
                    'number'      => (float)$v['number'],
                    'batch_name'  => isset($batch_data['batch_name'])?$batch_data['batch_name']:'',
                    'manufacture' => $batch_data['manufacture'],
                    'guarantee'   => $batch_data['guarantee'],
                    'validity'    => $batch_data['validity'],
                    'type'        => 7,
                    'purchase_id'  => $v['production_id'],
                    'purchase_info_id'   => $v['id'],
                    'createtime'  => time(),
                    'updatetime'  => time(),
                ];
            }
            //商品批次跟踪结束
        }
        //批次库存数据结束

        Db::startTrans();
        try {

            //序列号跟踪
            if(!empty($serial_log)){
                Db::name('kuyou_goods_serial_log')->insertAll($serial_log);
            }
            if(!empty($goods_stock_log)){
                Db::name('kuyou_goods_log')->insertAll($goods_stock_log);
            }
            //批次库存数据
            if(!empty($goods_batch_log)){
                Db::name('kuyou_goods_batch_log')->insertAll($goods_batch_log);
            }
            if(!empty($goods_batch_add)){
                Db::name('kuyou_goods_batch_stock')->insertAll($goods_batch_add);
            }
            if(!empty($goods_batch_edit)){
                foreach ($goods_batch_edit as $k=>$v){
                    Db::name('kuyou_goods_batch_stock')->where(['id'=>$k])->update(['stock'=>$v]);
                }
            }
            //批次库存数据结束

            if(!empty($serial_data)){
                (new GoodsSerial())->saveAll($serial_data);
            }
            if(!empty($goods_batch_info)){
                Db::name('kuyou_goods_batch_sale_info')->insertAll($goods_batch_info);
            }
            if(!empty($editstock)){
                (new GoodsStock())->saveAll($editstock);
            }
            if(!empty($goods_stock)){
                (new Goods())->saveAll($goods_stock);
            }

            $result = $model->where(['id'=>['in',$ids],'examine_status'=>'0'])
                ->update(['examine_status'=>1,'examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ['status'=>500,'msg'=>$e->getMessage()];
        }
        if(isset($result) && $result !== false){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'操作失败'];
        }
    }

    /**
     * 反审核
     * @param array $purchase_code
     * @return array
     */
    public static function examinef($ids = null){
        if(empty($ids)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        $model = new Outsourcing();
        $list = $model->where(['id'=>['in',$ids],'examine_status'=>'1'])->select();
        $production_id = $model->where(['id'=>['in',$ids],'examine_status'=>'1'])->column('id');

        foreach ($list as $list_k=>$list_v){
            $order = Db::name('kuyou_material')->where(['outsourcing_code'=>$list_v['purchase_code']])->column('id');
            if(!empty($order)){
                return ['status'=>400,'msg'=>'不能反审核已生成退料单的数据'];
            }
            $order = Db::name('kuyou_acceptance')->where(['outsourcing_code'=>$list_v['purchase_code']])->column('id');
            if(!empty($order)){
                return ['status'=>400,'msg'=>'不能反审核已生成验收单的数据'];
            }
        }

        $purchase_info_id = Db::name('kuyou_outsourcing_info')->where(['production_id'=>['in',$production_id]])->column('id');
        $info_list = Db::name('kuyou_outsourcing_info')->where(['production_id'=>['in',$production_id]])->select();

        $editstock = [];
        $goods_stock = [];
        $purchase_info = [];
        $serial_data = [];
        foreach ($info_list as $list_k=>$list_v){
            $picking = Db::name('kuyou_outsourcing')->where(['id'=>$list_v['production_id']])->find();
            if(!empty($list_v['period'])){
                $goods_serial = unserialize($list_v['period']);
                foreach ($goods_serial as $goods_serial_k=>$goods_serial_v){
                    $this_serial = Db::name('kuyou_goods_serial')->where(['serial'=>$goods_serial_v['serial']])->find();
                    if(empty($this_serial)){
                        return ['status'=>400,'msg'=>'序列号'.$goods_serial_v['serial'].'不存在'];
                    }
                    $serial_data[] = [
                        'id'=>$this_serial['id'],
                        'sale_id' => $picking['id'],
                        'sale_code' => $picking['purchase_code'],
                        'status' => $this_serial['old_status'],
                        'store_status' => $this_serial['old_store'],
                    ];
                }
            }

            $info_list[$list_k]['sales_order_id']    = $list_v['id'];
            $info_list[$list_k]['createtime']        = time();
            $info_list[$list_k]['updatetime']        = time();
            $stock_number = $list_v['basic_nmber'];
            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$list_v['goods_code']])->field('id,attribute_id,inventory,unit_id,goods_name')->find();
            $status = false;
            foreach ($goods_stock as $goods_stock_k=>$goods_stock_v){
                if($goods_stock_v['id']==$goods['id']){
                    $goods_stock[$goods_stock_k]['inventory'] = $goods_stock_v['inventory']+$stock_number;
                    $status = true;
                }
            }
            if(!$status){
                $goods_stock[] = [
                    'id'=>$goods['id'],
                    'inventory'=>$goods['inventory']+$stock_number,
                ];
            }
            //商品库存
            $where = [];
            $where['goods_code'] = $list_v['goods_code'];
            $where['stores_id'] = $list_v['stores_id'];
            if($list_v['goods_attr']>0){
                $goods_attr = $list_v['goods_attr'];
                if($goods_attr>0){
                    $where['attribute_id'] = $goods_attr;
                }
            }

            $stock = Db::name('kuyou_goods_stock')->where($where)->field('stock,id')->find();
            if($stock){
                $status = false;
                foreach ($editstock as $editstock_k=>$editstock_v){
                    if($editstock_v['id']==$stock['id']){
                        $editstock[$editstock_k]['stock'] += $stock_number;
                        $status = true;
                    }
                }
                if(!$status){
                    $editstock[] = [
                        'id'=>$stock['id'],
                        'stock'=>(round($stock['stock']+$stock_number,4))
                    ];
                }
            }else{
                if(empty($this_serial)){
                    return ['status'=>400,'msg'=>'库存数据错误,反审核失败'];
                }
            }
            $purchase_info[] = $list_v['id'];
        }

        //批次库存数据
        //获取设置
        $set= \think\Db::name('kuyou_sets')->field('type,name,value,is_checked,set')->select();
        $setList = [];
        foreach ($set as $set_k=>$set_v){
            if(!empty($set_v['set'])){
                $set_v['set'] = unserialize($set_v['set']);
            }
            $setList[$set_v['name']] = $set_v;
        }
        //数量价格格式化
        $number_decimal = $setList['number_decimal']['value'];
        $goods_serial = Db::name('kuyou_outsourcing_info')->where(['id'=>['in',$purchase_info_id]])->select();

        $goods_batch_add = [];$goods_batch_edit = [];
        foreach ($goods_serial as $k=>$v){
            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->field('id,goods_name,attribute_id,inventory,unit_id,batch')->find();
            if($goods['batch']==1){
                //先通过单位计算需修改多单位商品的库存数量
                if($goods['unit_id']==$v['goods_unit']){
                    $stock_number = $v['number'];
                }else{
                    $unit_conversion = Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$v['goods_unit']])->value('advance_rate');
                    if(empty($unit_conversion)){
                        if(empty($this_serial)){
                            return ['status'=>400,'msg'=>'商品单位信息查询失败'];
                        }
                    }else{
                        $stock_number = round(($v['number']*$unit_conversion),$number_decimal);
                    }
                }

                $where = [];
                $where['goods_id'] = $goods['id'];
                if($v['goods_attr']){
                    $where['attribute_id'] = $v['goods_attr'];
                }
                $where['stores_id'] = $v['stores_id'];
                $where['batch_id'] = $v['batch_id'];
                $goods_batch_stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                if(empty($goods_batch_stock)){
                    $status = false;
                    foreach ($goods_batch_add as $goods_batch_add_k=>$goods_batch_add_v){
                        if($goods_batch_add_v['batch_id']==$v['batch_id'] && $goods_batch_add_v['goods_id']==$goods['id'] && $goods_batch_add_v['attribute_id']==$v['attribute_id'] && $goods_batch_add_v['stores_id']==$v['stores_id']){
                            $goods_batch_add[$goods_batch_add_k]['stock'] += $stock_number;
                            $status = true;
                        }
                    }
                    if(!$status){
                        $goods_batch_add[] = [
                            'batch_id' => $v['batch_id'],
                            'goods_id' => $goods['id'],
                            'goods_code' => $v['goods_code'],
                            'attribute_id' => $v['goods_attr'],
                            'stores_id' => $v['stores_id'],
                            'stock' => $stock_number,
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                    }
                }else{
                    if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                        $goods_batch_edit[$goods_batch_stock['id']] += $stock_number;
                    }else{
                        $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']+$stock_number;
                    }
                }
            }
        }
        //批次库存数据结束

        Db::startTrans();
        try {
            //序列号跟踪
            if(!empty($purchase_info_id)){
                Db::name('kuyou_goods_serial_log')->where(['business_type'=>'15','purchase_id'=>['in',$purchase_info_id]])->delete();
            }
            //批次库存数据
            //删除批次跟踪
            if(!empty($purchase_info_id)){
                Db::name('kuyou_goods_batch_log')->where(['business_type'=>'15','order_id'=>['in',$purchase_info_id]])->delete();
            }
            if(!empty($goods_batch_edit)){
                foreach ($goods_batch_edit as $k=>$v){
                    Db::name('kuyou_goods_batch_stock')->where(['id'=>$k])->update(['stock'=>$v]);
                }
            }
            //批次库存数据结束
            if(!empty($serial_data)){
                (new GoodsSerial())->saveAll($serial_data);
            }
            if(!empty($purchase_info_id)){
                Db::name('kuyou_goods_batch_sale_info')->where(['purchase_info_id'=>['in',$purchase_info_id]])->delete();
                Db::name('kuyou_goods_log')->where(['business_type'=>'16','purchase_id'=>['in',$purchase_info_id]])->delete();
            }
            if(!empty($editstock)){
                (new GoodsStock())->saveAll($editstock);
            }
            if(!empty($goods_stock)){
                (new Goods())->saveAll($goods_stock);
            }
            $result = $model->where(['id'=>['in',$ids],'examine_status'=>'1'])
                ->update(['examine_status'=>'0','examine_id'=>0,'examine_time'=>'','operation_id'=>$adminId]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ['status'=>400,'msg'=>$e->getMessage()];
        }
        if(isset($result) && $result !== false){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>400,'msg'=>'反审核失败'];
        }
    }

}
